package cn.icare.cms.controller.restful;


import cn.icare.cms.DateUtil;
import cn.icare.cms.ImageUtil;
import cn.icare.cms.StringUtil;
import cn.icare.cms.aliyunsdk.PicUploadResult;
import cn.icare.cms.aliyunsdk.UploadPicService;
import cn.icare.cms.model.ro.AddAreaRO;
import cn.icare.cms.model.vo.rest.RespMsgVO;
import cn.icare.cms.qrcode.QRCodeUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.util.Date;

@CrossOrigin
@RestController
@RequestMapping(value = "/rest/upload")
@Api(tags = "REST文件上传")
public class UploadController extends BaseController {

    @Value("${cms.upload.physical-path}")
    private String physicalPath;
    /**
     * 文件保存目录的http发布地址
     */
    @Value("${cms.upload.web-path}")
    private String webPath;

    @Autowired
    UploadPicService uploadPicService;

    @PostMapping("/image")
    @ApiOperation(value = "上传图片", notes = "上传图片")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "文件", required = true, paramType = "query", dataTypeClass = MultipartFile.class),
            @ApiImplicitParam(name = "kind", value = "分类名称", required = false, paramType = "query", dataTypeClass = String.class)
    })
    public ResponseEntity<RespMsgVO> uploadImage(MultipartFile file, String kind)
//    public ResponseEntity<RespMsgVO> uploadImage(@RequestParam("file") MultipartFile file,
//                                                 @RequestParam("kind") String kindName
//    )
    {
        if (StringUtil.isEmpty(kind)) {
            kind = "image";
        }
        return uploadImageToAliyunOSS(file, kind);
    }

    /**
     * 商品主图与价格，合成一张图
     *
     * @throws IOException
     */
    @GetMapping("/getShareItemPic")
    @ApiOperation(value = "商品分享图片生成", notes = "商品分享图片生成")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "picUrl", value = "商品图片Url", required = true, paramType = "query", dataTypeClass = String.class),
            @ApiImplicitParam(name = "orignPrice", value = "原价", required = false, paramType = "query", dataTypeClass = String.class),
            @ApiImplicitParam(name = "newPrice", value = "现价", required = true, defaultValue = "1", paramType = "query", dataTypeClass = String.class)
    })
    public ResponseEntity<RespMsgVO> getShareItemPic(String picUrl, String orignPrice, String newPrice
    ) throws IOException {

        String newPicurl;
        try {
            String fileName;
            //生成的二维码的路径及名称
            // 商品主图
            String imageUrl = picUrl;
            URL url = new URL(imageUrl);
            String filePath=url.getFile();
            String dirName= DateUtil.formateToDateTime(new Date(),"yyyy-MM-dd");
            String filePre= DateUtil.formateToDateTime(new Date(),"yyyyMMddHHmmssSSS");
            if(filePath.indexOf("/")>=0)
            {
                fileName = dirName+"/"+"share_"+filePre+"_"+filePath.substring(filePath.lastIndexOf("/")+1);
            }
            else
            {
                fileName = dirName+"/"+"share_"+filePre+"_"+filePath;
            }
            String savePath = this.physicalPath + "/" + fileName;
            newPicurl = this.webPath + "/" + fileName;
            BufferedImage picImage = ImageIO.read(url);
            URL buttomUrl = this.getClass().getClassLoader().getResource("item_buttom.jpg");
            BufferedImage buttonImage = ImageIO.read(buttomUrl);
            String fontDir=this.getClass().getClassLoader().getResource("msyh.ttc").getPath();
            BufferedImage modifyImage =
                    ImageUtil.mergeImage(picImage, buttonImage, orignPrice, newPrice,fontDir);

            QRCodeUtil.mkdirs(savePath);
            ImageIO.write(modifyImage, "jpg", new File(savePath));
            return super.getRespOk(newPicurl);

        } catch (Exception e) {

            e.printStackTrace();
        }
        return super.getRespFail();
    }


    private ResponseEntity<RespMsgVO> uploadImageToAliyunOSS(MultipartFile file, String kindName) {
        String picUrl = "";
        if (!file.isEmpty()) {
            PicUploadResult picUploadResult = uploadPicService.upload(file, kindName);
            if (picUploadResult.getIsSuccess()) {
                return super.getRespOk(picUploadResult.getPicUrl());
            } else {
                return super.getRespFail("上传失败：" + picUploadResult.getError());
            }
        } else {
            return super.getRespFail("上传失败,因为文件为空");
        }
    }


    private ResponseEntity<RespMsgVO> uploadImageToLocal(MultipartFile file) {
        String picUrl = "";
        if (!file.isEmpty()) {
            String originalFilename = file.getOriginalFilename();
            String fileExt = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            //新文件名称： yyyyMMddHHmmSS
            String saveFileName = new java.text.SimpleDateFormat("yyyyMMddHHmmSS").format(new java.util.Date()) + "." + fileExt;
            String saveDirName = new java.text.SimpleDateFormat("yyyyMMdd").format(new java.util.Date());
            File saveFile = new File(physicalPath + saveDirName + "/" + saveFileName);
            System.out.println("上传文件物理路径：" + saveFile.getAbsolutePath());
            if (!saveFile.getParentFile().exists()) {
                saveFile.getParentFile().mkdirs();
            }
            try {
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(saveFile));
                out.write(file.getBytes());
                out.flush();
                out.close();
                picUrl = webPath + saveDirName + "/" + saveFileName;
                return super.getRespOk(picUrl);
            } catch (FileNotFoundException e) {
                e.printStackTrace();

                return super.getRespFail("上传失败," + e.getMessage());
            } catch (IOException e) {
                e.printStackTrace();
                return super.getRespFail("上传失败," + e.getMessage());
            }
        } else {
            return super.getRespFail("上传失败,因为文件为空");
        }


    }
}
